package com.zhangliang.oa.crud;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String servletPath = request.getServletPath();
        HttpSession session = request.getSession();
        if ("/index.jsp".equals(servletPath) || "/dept/login".equals(servletPath) || "/dept/exit".equals(servletPath)
                || "/dept/welcome".equals(servletPath) || (session != null && session.getAttribute("user") != null)) {
            filterChain.doFilter(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
